
import { useRouter } from 'expo-router';
import {
  StyleSheet,
  SafeAreaView,
  Dimensions,
  Linking,
  AppState,
  View,
  Text,
  Image
} from 'react-native';
import { useCameraPermissions, CameraView } from 'expo-camera';
import React, { useEffect, useState, useRef } from 'react';
export default function HomeScreen() {
  const [permission, requestPermission] = useCameraPermissions();
  const isPermissionGranted = Boolean(permission?.granted);
  const [widths, setWidths] = useState(390);
  const [heights, setHeights] = useState(800);
  const widthPx = 390;
  const heightPx = 844;

  const w = (value: number) => {
    return (value * widths) / widthPx
  }
  const h = (value: number) => {
    return (value * heights) / heightPx
  }
  useEffect(() => {
    Dimensions.addEventListener('change', () => {
      const { width, height } = Dimensions.get('window')
      setWidths(width)
      setHeights(height)
    })
  })
  const router = useRouter();
  useEffect(() => {
    if (!isPermissionGranted) {
      requestPermission();
    }
  }, []);
  const qrLock = useRef(false);//防止重复扫描
  const appstate = useRef(AppState.currentState);
  useEffect(() => {
    const subscription = AppState.addEventListener('change', nextAppState => {
      if (appstate.current.match(/inactive|background/) && nextAppState === 'active') {
        qrLock.current = false;
      }
      appstate.current = nextAppState;
    })
    return () => {
      subscription.remove();
    }
  }, [])

  return (
    <SafeAreaView style={StyleSheet.absoluteFillObject}>
      <View style={{
        position: 'absolute',
        top: h(30),
        left: w(15),
        width: w(360),
        height: h(40),
      }} >
        <Image source={require('@/assets/images/tops.png')} style={{
          width: w(340),
          height: h(40),
        }} >
        </Image>
      </View>
      <CameraView
        style={{
          position: 'absolute',
          top: h(80),
          left: w(15),
          width: w(360),
          height: h(600),
        }}
        facing="back"
        onBarcodeScanned={({ data }: any) => {
          if (data && !qrLock.current) {
            setTimeout(async () => {
              await Linking.openURL(data);
              console.log(data);
            }, 1000);
          }

        }}
      >
      </CameraView>

    </SafeAreaView>
  );
}
